import React from 'react';
import './crmWhitelist.less';
import { Layout, Breadcrumb, Icon, Button, Table, Checkbox, Modal, Input, Select, Form, Pagination, message } from 'antd';
import $ from 'jquery';
import Config from '../../../common/config';

const FormItem = Form.Item;
const config = new Config();
const { Header, Content, Footer, Sider } = Layout;
const Option = Select.Option;
const InputGroup = Input.Group;
const token = sessionStorage.getItem('token');
const keyword = sessionStorage.getItem('keyword');//前台权限判断

class CrmWhitelistForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            pagesize: 20,// 每页显示的页数
            goodsinfocount: 0,//客户来源条数
            pageindex: 1,// 当前页
            visible: false, //新增弹出框
            visible1: false, //删除弹出框
            visible2: false, //修改弹出框
            Inkey: "",// IP地址
            salestatus: "",//状态
            goodsinfolist: [], //列表
            selectedRowKeys: [],//选中的行
        }
    }

    componentDidMount() {
        this.GuestChannel()
    }

    //列表
    GuestChannel() {
        $.ajax({
            url: `${config.CrmSettings}/crm_ipallowed/GetIpAllowedList`,
            type: "post",
            headers: { Authorization: 'Bearer ' + token },
            data: {
                pagesize: this.state.pagesize,
                pageindex: this.state.pageindex,
                isenable: this.state.salestatus,
                ip: this.state.Inkey,
            },
            success: res => {
                if (res.code == 200) {
                    console.log('aaa', res);
                    this.setState({
                        goodsinfolist: res.data,
                        goodsinfocount: res.datacount,
                    });
                } else {
                    message.error('服务器繁忙，请稍后再试。', 1);
                }
            }
        })
    }
    // 分页
    changePage(pageindex) {
        this.setState({
            pageindex
        }, () => {
            this.GuestChannel();
        });
    }
    //改变每页条数
    handleSizeChange(current, pagesize) {
        this.setState({
            pageindex: 1,
            pagesize: pagesize
        }, () => {
            this.GuestChannel();
        });
    }

    //状态的改变事件
    salestatusChange(v) {
        this.setState({
            salestatus: v
        });
    }

    //搜索
    SearchProductInfoBtn(e) {
        const form = this.props.form;
        this.setState({
            pageindex: 1,
            Inkey: form.getFieldValue('txt_Inkey')
        }, () => {
            this.GuestChannel()
        });
    }

    //重置
    ResetBtn(e) {
        const form = this.props.form;
        this.props.form.resetFields();
        this.setState({
            salestatus: '',
            Inkey: ''
        }, () => {
            this.GuestChannel()
        });
    }

    //新增弹出框事件
    showModal() {
        this.setState({
            visible: true,
        });
    }
    handleOk() {
        this.props.form.validateFields(['adddescrip', 'addip', 'addisenable', 'addmark'], (err, values) => {
            console.log(values)
            if (!err) {
                $.ajax({
                    url: `${config.CrmSettings}/crm_ipallowed/AddIpAllowed`,
                    type: "post",
                    headers: { Authorization: 'Bearer ' + token },
                    data: {
                        descrip: values.adddescrip,
                        ip: values.addip,
                        isenable: values.addisenable,
                        mark: values.addmark,
                    },
                    success: res => {
                        console.log(res)
                        if (res.code == 200) {
                            this.GuestChannel()
                            this.setState({
                                visible: false,
                            });
                        } else if (res.code == 202) {
                            message.error('此IP名已存在，请重新填写！', 1);
                        } else {
                            message.error('服务器繁忙，请稍后再试。', 1);
                        }
                        this.props.form.resetFields(['adddescrip', 'addip', 'addisenable', 'addmark'])
                    }
                })
            } else {
                message.error('请正确填写必要的信息，再提交。', 1);
            }
        });
    }
    handleCancel() {
        this.setState({
            visible: false,
        });
        this.props.form.resetFields(['adddescrip', 'addip', 'addisenable', 'addmark'])
    }

    //删除弹出框事件
    showModal1() {
        if (this.state.selectedRowKeys.length === 0) {
            message.warning('请先选择要删除的数据！', 1);
        } else {
            this.setState({
                visible1: true,
            });
        }
    }
    handleOk1() {
        const { selectedRowKeys } = this.state;
        if (selectedRowKeys.length === 0) {
            message.warning('请先选择要删除的数据！', 1);
        } else {
            $.ajax({
                url: `${config.CrmSettings}/crm_ipallowed/DelIpAllowed`,
                type: "post",
                headers: { Authorization: 'Bearer ' + token },
                data: {
                    id: selectedRowKeys.toString()
                },
                success: res => {
                    console.log(res)
                    if (res.code == 200) {
                        message.success('删除成功！', 1);
                        this.setState({
                            pageindex: 1,
                            visible1: false,
                            selectedRowKeys: [],
                        }, () => this.GuestChannel());
                    } else {
                        message.error('服务器繁忙，请稍后再试', 1);
                    }
                }
            })
        }
    }
    handleCancel1() {
        this.setState({
            visible1: false,
        });
    }
    //修改弹出框事件
    modifyBlock(record) {
        this.props.form.setFieldsValue({
            descrip: record.descrip,
            ip: record.ip,
            isenable: record.isenable.toString(),
            mark: record.mark,
        });
        this.setState({
            visible2: true,
            id: record.id,
        });
    }
    handleOk2() {
        this.props.form.validateFields(['descrip', 'ip', 'isenable', 'mark'], (err, values) => {
            if (!err) {
                $.ajax({
                    url: `${config.CrmSettings}/crm_ipallowed/UpdateIpAllowed`,
                    type: "post",
                    headers: { Authorization: 'Bearer ' + token },
                    data: {
                        descrip: values.descrip,
                        ip: values.ip,
                        isenable: values.isenable,
                        mark: values.mark,
                        id: this.state.id,
                    },
                    success: res => {
                        console.log('long', res)
                        if (res.code == 200) {
                            this.GuestChannel()
                            this.setState({
                                visible2: false,
                            });
                        } else if (res.code == 202) {
                            message.error('此IP名已存在，请重新填写！', 1);
                        } else {
                            message.error('服务器繁忙，请稍后再试', 1);
                        }
                    }
                })
            } else {
                message.error('请填写必要的信息，再提交', 1);
            }
        });
    }
    handleCancel2() {
        this.setState({
            visible2: false,
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
            },
        };
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ selectedRowKeys });
            },
        };
        const columns = [{
            title: '地点描述',
            dataIndex: 'descrip',
            width: '25%',
        }, {
            title: 'IP地址',
            dataIndex: 'ip',
            width: '25%',
        }, {
            title: '备注',
            dataIndex: 'mark',
            width: '40%',
        }, {
            title: '操作',
            dataIndex: 'packing',
            width: '10%',
            render: (text, record) => {
                return keyword.includes('crm_ipallowedUpdateIpAllowed') ? <div><a onClick={this.modifyBlock.bind(this, record)}>修改</a></div> : '';
            }
        }
        ];

        return (
            <Form>
                <div className='goods-label'>
                    <div className='goods-label-cont clearfix'>
                        <div className='goods-label-cont-nav clearfix'>
                            <Breadcrumb separator=">">
                                <Breadcrumb.Item>系统设置</Breadcrumb.Item>
                                <Breadcrumb.Item>白名单设置</Breadcrumb.Item>
                            </Breadcrumb>
                        </div>
                        <div className='member-content-Search clearfix'>
                            <div className='addetd addetd-a indtner yorttr'>
                                <InputGroup compact>
                                    <Input addonBefore="IP状态" />
                                    <Select value={this.state.salestatus} onChange={this.salestatusChange.bind(this)}>
                                        <Option value="0">IP禁用</Option>
                                        <Option value="1">IP启用</Option>
                                    </Select>
                                </InputGroup>
                            </div>
                            <div className='addetd addetd-z' style={{ marginLeft: 20 }}>
                                <FormItem>
                                    {
                                        getFieldDecorator('txt_Inkey')(
                                            <Input className='addetd-a-r' addonBefore="IP地址" placeholder="请输入" />
                                        )
                                    }
                                </FormItem>
                            </div>
                            <Button type="primary" style={{ marginLeft: 50 }} className='member-button' icon="search" onClick={this.SearchProductInfoBtn.bind(this)}>搜索</Button>
                            <Button type="primary" className='member-button' icon="reload" onClick={this.ResetBtn.bind(this)}>重置</Button>
                        </div>
                        <div className='chengge-e  your_sa' style={{ marginBottom: 20 }}>
                            {keyword.includes('crm_ipallowedAddIpAllowed') ?
                                <Button className='member-button-aa' onClick={this.showModal.bind(this)} type='primary' style={{ marginLeft: 20 }}><Icon type="plus" />新增</Button>
                                : ''}
                            <Modal title="新增" visible={this.state.visible}
                                onOk={this.handleOk.bind(this)} onCancel={this.handleCancel.bind(this)}
                                maskClosable={false}
                            >
                                <div className='baoigg'>
                                    <FormItem
                                        {...formItemLayout}
                                        label="地点描述"
                                        hasFeedback
                                    >
                                        {getFieldDecorator('adddescrip', {
                                            initialValue: "",
                                            validateTrigger: 'onBlur',
                                            rules: [{
                                                required: true, max: 20, message: '地点描述不能为空，不能超过20个字',
                                            }],
                                        })(
                                            <Input placeholder="请输入地点描述，不超过20个字" />
                                            )}
                                    </FormItem>
                                    <FormItem
                                        {...formItemLayout}
                                        label="IP地址"
                                        hasFeedback
                                    >
                                        {getFieldDecorator('addip', {
                                            initialValue: "",
                                            validateTrigger: 'onBlur',
                                            rules: [{
                                                required: true, max: 20, message: 'IP地址不能为空，不能超过20个字',
                                            }],
                                        })(
                                            <Input placeholder="请输入IP地址，不超过20个字" />
                                            )}
                                    </FormItem>
                                    <FormItem
                                        {...formItemLayout}
                                        label="IP状态"
                                    >
                                        {getFieldDecorator('addisenable', {
                                            initialValue: "1",
                                        })(
                                            <Select>
                                                <Option value="1">IP启用</Option>
                                                <Option value="0">IP禁用</Option>
                                            </Select>
                                            )}
                                    </FormItem>
                                    <FormItem
                                        {...formItemLayout}
                                        label="备注"
                                    >
                                        {getFieldDecorator('addmark', {
                                            initialValue: "",
                                            validateTrigger: 'onBlur',
                                            rules: [{
                                                max: 100, message: '备注不能超过100个字',
                                            }],
                                        })(
                                            <Input type="textarea" style={{ resize: 'none' }} rows={5} placeholder="请输入备注，不超过100个字" />
                                            )}
                                    </FormItem>
                                </div>
                            </Modal>
                            {keyword.includes('crm_ipallowedDelIpAllowed') ?
                                <Button className='member-button-aa' onClick={this.showModal1.bind(this)} style={{ width: 100 }} type='primary'>删除</Button>
                                : ''}
                            <Modal title="删除" visible={this.state.visible1}
                                onOk={this.handleOk1.bind(this)} onCancel={this.handleCancel1.bind(this)}
                                maskClosable={false}
                            >
                                <div className='delets_gg'>
                                    <p className='delets_gg1'>温馨提示</p>
                                    <p>删除后不可恢复，是否继续删除？</p>
                                </div>
                            </Modal>
                            <Modal title="修改" visible={this.state.visible2}
                                onOk={this.handleOk2.bind(this)} onCancel={this.handleCancel2.bind(this)}
                                maskClosable={false}
                            >
                                <div className='baoigg'>
                                    <FormItem
                                        {...formItemLayout}
                                        label="地点描述"
                                        hasFeedback
                                    >
                                        {getFieldDecorator('descrip', {
                                            validateTrigger: 'onBlur',
                                            rules: [{
                                                required: true, max: 20, message: '地点描述不能为空，不能超过20个字',
                                            }],
                                        })(
                                            <Input placeholder="请输入地点描述，不超过20个字" />
                                            )}
                                    </FormItem>
                                    <FormItem
                                        {...formItemLayout}
                                        label="IP地址"
                                        hasFeedback
                                    >
                                        {getFieldDecorator('ip', {
                                            validateTrigger: 'onBlur',
                                            rules: [{
                                                required: true, max: 20, message: 'IP地址不能为空，不能超过20个字',
                                            }],
                                        })(
                                            <Input placeholder="请输入IP地址，不超过20个字" />
                                            )}
                                    </FormItem>
                                    <FormItem
                                        {...formItemLayout}
                                        label="IP状态"
                                    >
                                        {getFieldDecorator('isenable', {
                                        })(
                                            <Select>
                                                <Option value="1">IP启用</Option>
                                                <Option value="0">IP禁用</Option>
                                            </Select>
                                            )}
                                    </FormItem>
                                    <FormItem
                                        {...formItemLayout}
                                        label="备注"
                                    >
                                        {getFieldDecorator('mark', {
                                            validateTrigger: 'onBlur',
                                            rules: [{
                                                max: 100, message: '备注不能超过100个字',
                                            }],
                                        })(
                                            <Input type="textarea" style={{ resize: 'none' }} rows={5} placeholder="请输入备注，不超过100个字" />
                                            )}
                                    </FormItem>
                                </div>
                            </Modal>
                        </div>
                        <div className='allgoods-table clearfix'>
                            <Table
                                rowKey="id"
                                rowSelection={rowSelection}
                                columns={columns}
                                dataSource={this.state.goodsinfolist}
                                pagination={false}
                                bordered
                            />
                        </div>
                        <div className='goods-label-let'>
                            <div className="floor-ppagi">
                                {
                                    this.state.goodsinfocount == 0 ?
                                        <p className="floor-ppagip">
                                            共{this.state.goodsinfocount}条记录
                                </p> :
                                        <p className="floor-ppagip">
                                            当前显示
                                    {this.state.pagesize * (this.state.pageindex - 1) + 1}—
                                    {this.state.pagesize * this.state.pageindex < this.state.goodsinfocount ? this.state.pagesize * this.state.pageindex : this.state.goodsinfocount}条记录，
                                    共{this.state.goodsinfocount}条记录
                                </p>
                                }
                                <Pagination
                                    current={this.state.pageindex}
                                    total={this.state.goodsinfocount || 1}
                                    defaultPageSize={this.state.pagesize}
                                    onChange={this.changePage.bind(this)}
                                    showSizeChanger
                                    pageSizeOptions={['20', '50', '100']}
                                    onShowSizeChange={(current, pagesize) => this.handleSizeChange(current, pagesize)}
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </Form>
        )
    }
}

const CrmWhitelist = Form.create()(CrmWhitelistForm);
export default CrmWhitelist;